package com.jxccp.ui.service;

import android.content.Context;
import android.text.TextUtils;

import com.jxccp.im.callback.JXEventListner;
import com.jxccp.im.callback.JXMessageCallback;
import com.jxccp.im.callback.JXUserSelfQueueListener;
import com.jxccp.im.chat.common.message.JXConversation;
import com.jxccp.im.chat.common.message.JXMessage;
import com.jxccp.im.chat.common.message.JXMessageAttribute;
import com.jxccp.im.chat.common.message.TextMessage;
import com.jxccp.im.chat.manager.JXEventNotifier;
import com.jxccp.im.chat.manager.JXImManager;
import com.jxccp.im.util.log.JXLog;
import com.jxccp.ui.JXUiHelper;
import com.jxccp.ui.R;
import com.jxccp.ui.listeners.JXDemoMessageListener;
import com.jxccp.ui.utils.JXContextWrapper;
import com.jxccp.ui.utils.JXNotificationUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class JXNotifyManager {

    private static JXNotifyManager jxNotifyManager;

    private Context applicationContext ;

    private boolean listnerAdded = false;

    private List<JXDemoMessageListener> sendMessageListeners = new ArrayList<JXDemoMessageListener>();

    public JXNotifyManager() {
    }

    public static JXNotifyManager getInstance() {
        if (null == jxNotifyManager) {
            synchronized (JXUiHelper.class) {
                if (null == jxNotifyManager) {
                    jxNotifyManager = new JXNotifyManager();
                }
            }
        }
        return jxNotifyManager;
    }

    public Context getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(Context applicationContext) {
        this.applicationContext = applicationContext;
        Locale mLocate = JXUiHelper.getInstance().getLanguge();
        this.applicationContext = JXContextWrapper.wrap(this.applicationContext, mLocate);
        if (!listnerAdded){
            addListner();
        }
    }

    private void addListner(){
        JXLog.d("[JXNotifyManager.addListner] add it.");
        JXImManager.Message.getInstance().registerEventListener(messageEventListner);
        JXImManager.McsUser.getInstance().addUserSelfQueueListeners(jxUserSelfQueueListener);
        JXImManager.Message.getInstance().setMessageCallback(messageCallback);
        listnerAdded = true;
    }

    public void removeLintner(){
        JXImManager.Message.getInstance().removeEventListener(messageEventListner);
        JXImManager.McsUser.getInstance().removeUserSelfQueueListeners(jxUserSelfQueueListener);
        JXImManager.Message.getInstance().setMessageCallback(null);
        listnerAdded = false;
    }

    /**
     * 新消息接收到时的监听器
     */
    JXEventListner messageEventListner = new JXEventListner() {
        @Override
        public void onEvent(final JXEventNotifier eventNotifier) {
            JXLog.d("[JXNotifyManager.messageEventListner] , eventNotifier:"+eventNotifier.getEvent());
            final JXMessage message = (JXMessage)eventNotifier.getData();
            switch (eventNotifier.getEvent()) {
                case MESSAGE_NEW:
                case MESSAGE_OFFLINE:
                case MESSAGE_REVOKE:
                    JXLog.d("[JXNotifyManager.messageEventListner], has new message incoming.");
                    String type = (String)message.getAttributes().get(JXMessageAttribute.TYPE.value());
                    if (!JXUiHelper.getInstance().isNotifyEndMsg() && !TextUtils.isEmpty(type) &&
                            (type.equals(JXMessageAttribute.TYPE_VALUE_EVALUATED)
                                    || type.equals(JXMessageAttribute.TYPE_VALUE_ENDED)
                                    || type.equals(JXMessageAttribute.TYPE_VALUE_AUTO_CLOSE_FOR_AGENT)
                                    || type.equals(JXMessageAttribute.TYPE_VALUE_AUTO_CLOSE_FOR_VISITOR)
                                    || message.getType() == JXMessage.Type.EVALUATION)) {
                        if (JXUiHelper.getInstance().isChatPage()){
                            if (eventNotifier.getEvent() != JXEventNotifier.Event.MESSAGE_REVOKE) {
                                JXNotificationUtils.vibrate(getApplicationContext());
                            }
                        }
                        JXConversation conversation = JXImManager.Conversation.getInstance()
                                .getConversation(message.getSuborgId(), JXMessage.ChatType
                                        .CUSTOMER_SERVICE);
                        if (conversation != null){
                            conversation.setUnreadCount(conversation.getUnreadCount()-1);
                            conversation.updateUnreadCount(conversation.getUnreadCount());
                        }
                        return;
                    }
                    if(type !=null && type.equals("S")){
                        if (JXUiHelper.getInstance().isChatPage()){
                            JXNotificationUtils.vibrate(getApplicationContext());
                        }
                        return;
                    }
                    if ((!JXUiHelper.getInstance().isChatPage() || (!TextUtils.isEmpty(message.getSuborgId())
                            &&!JXUiHelper.getInstance().getSuborgId().equals
                            (message.getSuborgId()))) && !JXUiHelper.getInstance().isConversationPage()) {
                        if (message instanceof TextMessage && JXImManager.Config.getInstance().isHKBN()){
                            // 收到扩展type为 ACFV ACFA 且是自动结束消息做多语言匹配
                            Object attrType = message.getAttributes().get(JXMessageAttribute.TYPE.value());
                            if (attrType != null && JXMessageAttribute.TYPE_VALUE_AUTO_CLOSE_FOR_VISITOR.equals(attrType)) {
                                ((TextMessage)message).setContent(getApplicationContext().getString(R.string.jx_auto_end_message));
                            }
                            if (attrType != null && JXMessageAttribute.TYPE_VALUE_AUTO_CLOSE_FOR_AGENT.equals(attrType)) {
                                ((TextMessage)message).setContent(getApplicationContext().getString(R.string.jx_auto_end_message_by_agent));
                            }
                        }
                        JXNotificationUtils.showIncomingMessageNotify(
                                getApplicationContext(), message);
                    }
                    if (JXUiHelper.getInstance().isConversationPage() || JXUiHelper.getInstance().isChatPage()){
                        if (eventNotifier.getEvent() != JXEventNotifier.Event.MESSAGE_REVOKE) {
                            JXNotificationUtils.vibrate(getApplicationContext());
                        }
                    }

                    break;
                case MESSAGE_PUSH:
                    if (JXUiHelper.getInstance().msgBoxEnable()){
                        int count = JXUiHelper.getInstance().getMessageBoxUnreadCount();
                        JXUiHelper.getInstance().setMessageBoxUnreadCount(count+1);
                        final JXMessage jxmessage = (JXMessage)eventNotifier.getData();
                        JXNotificationUtils.showMessagePushNotify(getApplicationContext(), jxmessage);
                    }
                    break;
                default:
                    break;
            }
        }
    };


    JXUserSelfQueueListener jxUserSelfQueueListener = new JXUserSelfQueueListener() {

        @Override
        public void onUserSelfQueueUpdate(String skillsId, int currentPosition, String queueMsg) {
            JXUiHelper.getInstance().setCurrentPosition(currentPosition);
            JXUiHelper.getInstance().setQuqueMsg(queueMsg);
        }

        @Override
        public void onUserSelfStatus(String skillsId, int status, String nickName) {
            if (status != JXUserSelfQueueListener.USER_STATUS_WAITING
                    && status != JXUserSelfQueueListener.USER_STATUS_PENDING) {
                JXUiHelper.getInstance().setCurrentPosition(-1);
            }
            if(status == JXUserSelfQueueListener.USER_STATUS_RECALL){
                if (!JXUiHelper.getInstance().isChatPage()) {
                    JXNotificationUtils.notifyRecallIncoming(getApplicationContext(), skillsId);
                }
            }
        }

        @Override
        public void onEnded(String skillsId, int reasonCode) {
            JXUiHelper.getInstance().setCurrentPosition(-1);
        }
    };

    JXMessageCallback messageCallback = new JXMessageCallback() {
        @Override
        public void onSuccess(JXMessage message) {
            for (JXDemoMessageListener listener : sendMessageListeners) {
                listener.onSuccess(message);
            }
        }

        @Override
        public void onError(JXMessage message, int code, String reason) {
            for (JXDemoMessageListener listener : sendMessageListeners) {
                listener.onError(message, code, reason);
            }
        }

        @Override
        public void onTransfered(JXMessage message, long totalSize, long currentSize) {
            for (JXDemoMessageListener listener : sendMessageListeners) {
                listener.onTransfered(message, totalSize, currentSize);
            }
        }
    };

    public void addMessagListener(JXDemoMessageListener listener) {
        if (listener != null) {
            if (!sendMessageListeners.contains(listener)) {
                sendMessageListeners.add(listener);
            }
        }
    }

    public void removeMessageListener(JXDemoMessageListener listener) {
        if (listener != null) {
            sendMessageListeners.remove(listener);
        }
    }

}
